package com.zsgeek.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ValidateLoginFilter implements Filter {

	private ServletContext servletContext;

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		// 获取配置需要登录的页面地址
		String url = servletContext.getInitParameter("validate_login");
		String common_page = servletContext.getInitParameter("common_page");
		// 获取配置的登录页面
		String login = servletContext.getInitParameter("login");
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		// 获取当前的 session
		HttpSession session = req.getSession();
		// 获取 ServletPath
		String path = req.getServletPath();
//		System.out.println("当前访问的是：" + path);
		// System.out.println("需要登录访问的地址是：" + url);
		// 判断当前访问的路径，是否在配置的需要登录的页面地址中。
		if (path.indexOf("sysadmin") != -1) {
			// 判断当前访问的路径，是否在配置的需要登录的页面地址中。
			if ((url.indexOf(path) != -1
					&& session.getAttribute("user") != null)||(url.indexOf(path) != -1)) {
				chain.doFilter(request, response);
			} else if (common_page.indexOf(path) != -1) {
				chain.doFilter(request, response);
			} else {
				System.out.println("被拦截了....");
				resp.sendRedirect(req.getContextPath() + login);
			}
		} else {
			chain.doFilter(request, response);
		}
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		this.servletContext = config.getServletContext();
	}

}
